package org.wii.base.web;

import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.WebRequest;
import org.wii.base.bean.ResultBean;
import org.wii.base.exception.IWiiException;
import org.wii.base.exception.constant.CommonExceptionExceptionEnum;

import java.util.Map;

/**
 * 自定义错误属性
 * @author tanghong on 2022/12/23
 */
public class CustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions attributeOptions) {
        Map<String, Object> defaultErrorAttributes = super.getErrorAttributes(webRequest, attributeOptions);
        Throwable throwable = this.getError(webRequest);
        if (!(throwable instanceof IWiiException)) {
            Integer status = (Integer) defaultErrorAttributes.get("status");
            HttpStatus resolve = HttpStatus.resolve(status);
            switch (resolve) {
                case NOT_FOUND:
                    String path = (String) defaultErrorAttributes.get("path");
                    return ResultBean.result(CommonExceptionExceptionEnum.NOT_FOUND.getCode(), path).toMap();
                default:
                    String error = (String) defaultErrorAttributes.get("error");
                    return ResultBean.result(CommonExceptionExceptionEnum.UNKNOWN.getCode(), error).toMap();
            }
        }
        return defaultErrorAttributes;
    }

}

